//
//  XMGADViewController.m
//  BuDeJie19
//
//  Created by hjj on 2016/12/3.
//  Copyright © 2016年 hjjuny. All rights reserved.
//

/*
 组件化开发
 
 cocoapods:管理第三方框架，集成第三方框架
 
 cocoapods使用步骤： 命令行
 1.创建Podfile文件（描述当前工程需要哪些框架） pod init
 2.打开Podfile进行描述 open
 3.pod search AFN
 4.pod install
 
 
 使用cocoapods好处？1.更新框架 2.自动引入所依赖其他框架 3.组件(小功能框架)化开发 4.优化代码内存容量
 
 ijkplayer:直播 100M
 
 */

#define code2 @"phcqnauGuHYkFMRquANhmgN_IauBThfqmgKsUARhIWdGULPxnz3vndtkQW08nau_I1Y1P1Rhmhwz5Hb8nBuL5HDknWRhTA_qmvqVQhGGUhI_py4MQhF1TvChmgKY5H6hmyPW5RFRHzuET1dGULnhuAN85HchUy7s5HDhIywGujY3P1n3mWb1PvDLnvF-Pyf4mHR4nyRvmWPBmhwBPjcLPyfsPHT3uWm4FMPLpHYkFh7sTA-b5yRzPj6sPvRdFhPdTWYsFMKzuykEmyfqnauGuAu95Rnsnbfknbm1QHnkwW6VPjujnBdKfWD1QHnsnbRsnHwKfYwAwiu9mLfqHbD_H70hTv6qnHn1PauVmynqnjclnj0lnj0lnj0lnj0lnj0hThYqniuVujYkFhkC5HRvnB3dFh7spyfqnW0srj64nBu9TjYsFMub5HDhTZFEujdzTLK_mgPCFMP85Rnsnbfknbm1QHnkwW6VPjujnBdKfWD1QHnsnbRsnHwKfYwAwiuBnHfdnjD4rjnvPWYkFh7sTZu-TWY1QW68nBuWUHYdnHchIAYqPHDzFhqsmyPGIZbqniuYThuYTjd1uAVxnz3vnzu9IjYzFh6qP1RsFMws5y-fpAq8uHT_nBuYmycqnau1IjYkPjRsnHb3n1mvnHDkQWD4niuVmybqniu1uy3qwD-HQDFKHakHHNn_HR7fQ7uDQ7PcHzkHiR3_RYqNQD7jfzkPiRn_wdKHQDP5HikPfRb_fNc_NbwPQDdRHzkDiNchTvwW5HnvPj0zQWndnHRvnBsdPWb4ri3kPW0kPHmhmLnqPH6LP1ndm1-WPyDvnHKBrAw9nju9PHIhmH9WmH6zrjRhTv7_5iu85HDhTvd15HDhTLTqP1RsFh4ETjYYPW0sPzuVuyYqn1mYnjc8nWbvrjTdQjRvrHb4QWDvnjDdPBuk5yRzPj6sPvRdgvPsTBu_my4bTvP9TARqnam"

/*
    基本URL：http://mobads.baidu.com/cpro/ui/mads.php
    code2 = code2
    http://mobads.baidu.com/cpro/ui/mads.php ?code2=
 
 
 */

#import "XMGADViewController.h"
#import <AFNetworking.h>
#import "XMGADItem.h"
#import <MJExtension/MJExtension.h>
#import <UIImageView+WebCache.h>
#import "XMGTabBarController.h"



/*
    占位视图：当一个界面层次结构确定，但是其中某一个结构尺寸不确定（层次结构多）
 */
@interface XMGADViewController ()
@property (weak, nonatomic) IBOutlet UIButton *jumpButton;
@property (weak, nonatomic) IBOutlet UIImageView *lauuchImageView;
@property (weak, nonatomic) IBOutlet UIView *containerView;
@property (nonatomic, strong) XMGADItem *item;
@property (nonatomic, weak) NSTimer *timer;
@end

@implementation XMGADViewController
- (IBAction)jump:(id)sender {
    // 倒计时结束
    XMGTabBarController *tabBarVc = [[XMGTabBarController alloc] init];
    // 进入到主界面
    [UIApplication sharedApplication].keyWindow.rootViewController = tabBarVc;
    
    // 销毁定时器
    [_timer invalidate];
    _timer = nil;

}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    // 设置启动图片
    [self setupLaunchImageView];
    
    // 展示广告数据 => 从服务器去取 => 接口文档 => AFN => cocoapods
    [self loadADData];
    
    // 创建定时器
    _timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timeChange) userInfo:nil repeats:YES];
}

// 每隔一秒就会调用
- (void)timeChange
{
    static int count = 1;
    
    count--;
    
    // 设置按钮文字
    [_jumpButton setTitle:[NSString stringWithFormat:@"跳过(%d)",count] forState:UIControlStateNormal];
    
    if (count == -1) {
        [self jump:nil];
    }
    
}

// 请求数据 => 接口文档 => AFN发送请求 => 解析数据 => 1.写成plist 2.在线解析 => 设计模型 => 字典转模型 => 直接把模型展示到界面

#pragma mark - 加载广告数据
- (void)loadADData
{
    /*
        技巧：如果想知道一个类有哪些东西，跳类
        想知道这个类做了什么事情，跳方法
     */
    
    // 1.创建请求会话管理者
    AFHTTPSessionManager *mgr = [AFHTTPSessionManager xmg_manager];
    
    // 2.拼接参数
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"code2"] = code2;
    
    // failed: unacceptable content-type: text/html
    
    // 3.发送请求
    [mgr GET:@"http://mobads.baidu.com/cpro/ui/mads.php" parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, NSDictionary * _Nullable responseObject) {
        // 获取广告字典
        NSDictionary *adDict = [responseObject[@"ad"] firstObject];
        
        // 字典转模型
        XMGADItem *item = [XMGADItem mj_objectWithKeyValues:adDict];
        _item = item;
        
        // 创建UIImageView
        UIImageView *imageView = [[UIImageView alloc] init];
        imageView.userInteractionEnabled = YES;
        CGFloat h = 0;
        if (item.w > 0) {
            h = XMGScreenW / item.w * item.h;
        }
        imageView.frame = CGRectMake(0, 0, XMGScreenW, h);
//        imageView
        [imageView sd_setImageWithURL:[NSURL URLWithString:item.w_picurl]];
        [_containerView addSubview:imageView];
        
        // 添加点按手势
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tap)];
        [imageView addGestureRecognizer:tap];
        
        // 解析数据 => 写成plist
//        [responseObject writeToFile:@"/Users/xmg5/Desktop/课堂共享/03-项目/1018/代码/02-广告/ad.plist" atomically:YES];
        
        
//        NSLog(@"%@",responseObject);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
       
        NSLog(@"%@",error);
        
    }];
    
}

#pragma mark - 点击广告图片就会调用
- (void)tap
{
    // 进入广告界面
    // safari
    NSURL *url = [NSURL URLWithString:_item.ori_curl];
    
    if ([[UIApplication sharedApplication] canOpenURL:url]) {
        [[UIApplication sharedApplication] openURL:url];
    }
}

- (void)setupLaunchImageView
{
    // 根据屏幕去加载不同图片
    // 6P LaunchImage-800-Portrait-736h@3x
    // 6 LaunchImage-800-667h@2x
    
    // 6P: 736 6 : 667  5 : 568 4 : 480
    UIImage *image = nil;
    if (iPhone6P) {
        image = [UIImage imageNamed:@"LaunchImage-800-Portrait-736h@3x"];
    } else if (iPhone6) {
        image = [UIImage imageNamed:@"LaunchImage-800-667h"];
    } else if (iPhone5) {
        image = [UIImage imageNamed:@"LaunchImage-700-568h"];
    } else if (iPhone4) {
        image = [UIImage imageNamed:@"LaunchImage-700"];
    }
    
    _lauuchImageView.image = image;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
